﻿using CefSharp;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartForm.Common
{
    public class ChromeBrowserUtil
    {
        public delegate object MethodInvokerNetJs(ChromiumWebBrowser chromeBrowser, Form form);
        public static ChromiumWebBrowser InitializeChromium(string url, Control webControl)
        {
            try
            {
                ChromiumWebBrowser chromeBrowser;
                if (!Cef.IsInitialized)
                {
                    CefSettings settings = new CefSettings();
                    settings.LogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"log\CefGlue.log");
                    settings.CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"cache");
                    settings.CommandLineArgsDisabled = true;
                    settings.Locale = "zh_CN";
                    settings.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
                    settings.UserDataPath = "/userData";
                    Cef.Initialize(settings);
                }
                chromeBrowser = new ChromiumWebBrowser(url.StartsWith("http://") || url.StartsWith("https://") ? url : Application.StartupPath + url);
                chromeBrowser.Dock = DockStyle.Fill;
                BrowserSettings browserSettings = new BrowserSettings();
                browserSettings.FileAccessFromFileUrls = CefState.Enabled;
                browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
                browserSettings.WebSecurity = CefState.Enabled;
                chromeBrowser.BrowserSettings = browserSettings;
                webControl.Controls.Add(chromeBrowser);
                Control.CheckForIllegalCrossThreadCalls = false;
                CefSharpSettings.LegacyJavascriptBindingEnabled = true;
                return chromeBrowser;
            }
            catch (Exception ex)
            {
                Console.WriteLine("InitializeChromium url：" + url + "，Error：" + ex.ToString());
                LogUtil.WriteLog("InitializeChromium", ex);
                return null;
            }
        }
    }
}
